// index.js

import {
	accountLogin,
	userInfo,
	uploadAvatarUrl,
	purchaseInfo
} from '../../api/api'
import {
	toast
} from '../../utils/wxApi'
import {
	maskPhoneNumber
} from '../../utils/util'

// 四舍五入到角(保留一位小数),整数不处理
function roundToJiao(value) {
	if (value == null || value === '') return 0
	const num = Number(value)
	if (isNaN(num)) return 0
	// 如果是整数,直接返回
	if (Number.isInteger(num)) return num
	// 如果是小数,四舍五入到一位小数
	return Math.round(num * 10) / 10
}

Page({
	data: {
		user: {},
		payInfo: {},
		userInfo: {},
		avatarUrl: wx.getStorageSync('avatarUrl'),
		token: wx.getStorageSync('token'),
		list: []
	},
	onLoad() {

		this.getData()
	},
	onPullDownRefresh() {
		this.getData()
		wx.stopPullDownRefresh()
	},
	getData() {
		wx.showLoading({
			title: '加载中',
		})
		wx.hideLoading()
		this.getUserInfo()
		this.getPurchaseInfo()
		// this.automaticLogon().then(res => {
		//     wx.hideLoading()
		//     this.getUserInfo()
		//     this.getPurchaseInfo()
		// }).catch(err => {
		//     wx.hideLoading()
		// })
	},
	toDetail(e) {
		console.log(e?.currentTarget?.dataset?.id)
		const storeId = e?.currentTarget?.dataset?.id;
		const storeName = e?.currentTarget?.dataset?.name || '';
		const username = e?.currentTarget?.dataset?.user || '';
		if (!storeId) return toast('缺少店铺ID')
		wx.navigateTo({
			url: `/pages/reconciliation/reconciliation?storeId=${storeId}&storeName=${encodeURIComponent(storeName)}&username=${encodeURIComponent(username)}`,
		})
	},
	
	
	

	onChooseAvatar(e) {

		wx.setStorageSync('avatarUrl', e.detail.avatarUrl);
		
		this.setData({
			avatarUrl: e.detail.avatarUrl
		})
		 wx.uploadFile({
		             url: "https://ceshiweb.picaime.com/api/User/uploadAvatarUrl",
		             filePath:  e.detail.avatarUrl,
		             name: 'file',
					 header: {
					                 'token':  wx.getStorageSync('token')
					  },
		             formData: {},
		             success: (res) => {
		     
		             },
		         });
			
			// uploadAvatarUrl({
			// 	avatarUrl: e.detail.avatarUrl
			// }, {
			// 	showLoading: true
			// }).then(res => {

			// })

		// wx.request({
		// 	url: 'https://ceshiweb.picaime.com/api/User/uploadAvatarUrl',
		// 	data: {
		// 		avatarUrl: e.detail.avatarUrl
		// 	},
		// 	success: function(res) {

		// 	}

		// })
	},

	getUserProfile: function(e) {
		// 推荐使用 getUserProfile 获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认  
		// 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗  
		if (e.detail.userInfo) {
			// 用户按了允许授权按钮  
			this.setData({
				userInfo: e.detail.userInfo
			})
		} else {
			// 用户按了拒绝按钮  
			wx.showToast({
				title: '用户拒绝授权',
				icon: 'none'
			})
		}
	},



	getCode: function() {
		let that = this
		wx.login({
			success(res) {
				if (res.code) {
					//发起网络请求
					wx.request({
						url: 'https://ceshiweb.picaime.com/api/Wx/wxLogin',
						data: {
							code: res.code
						},
						success: function(res) {
							wx.setStorageSync('openid', res.data.data.openid);
							console.log(wx.getStorageSync('openid'))
							that.setData({
								openid: res.data.data.openid,
							});
						}

					})
				} else {
					console.log('登录失败1！' + res.errMsg)
				}
			}
		})
	},

	getPhoneNumber(e) {
		let that = this
		wx.request({
			url: 'https://ceshiweb.picaime.com/api/Wx/wxGetPhoneOrInfo',
			data: {
				code: e.detail.code,
				openid: wx.getStorageSync('openid')
			},
			success: function(res) {
				wx.setStorageSync('token', res.data.data)

				that.setData({
					token: res.data.data,
				});

				that.getUserInfo()
				that.getPurchaseInfo()
				
				// 登录成功后检查是否需要重定向
				const redirectUrl = wx.getStorageSync('redirectUrl');
				if (redirectUrl) {
					wx.removeStorageSync('redirectUrl');
					setTimeout(() => {
						wx.redirectTo({
							url: redirectUrl,
							fail: () => {
								// 如果redirectTo失败，尝试使用reLaunch
								wx.reLaunch({
									url: redirectUrl
								});
							}
						});
					}, 500);
				}
			}
		})



    data: {
      // ...其他数据
      promoClosed: wx.getStorageSync('promoClosed') || false
    }
		// this.getUserInfo()
		// this.getPurchaseInfo()

	},




	//获取用户信息
	getUserInfo: function() {
		userInfo({}, {
			showLoading: true
		}).then(res => {
			const {
				userinfo = {}, pay = {}
			} = res?.data || {};
			this.setData({
				user: {
					avatar: userinfo?.avatar,
					mobile: maskPhoneNumber(userinfo?.mobile),
					nickname: userinfo?.nickname
				},
				payInfo: {
					paying: roundToJiao(pay.paying),
					payed: roundToJiao(pay.payed),
					purchase: roundToJiao(pay.purchase)
				}
			})
		})
	},
	getPurchaseInfo() {
		purchaseInfo({}, {
			showLoading: true
		}).then(res => {
			if (!res?.data) return
			// 对列表数据进行四舍五入处理
			const processedList = res.data.map(item => ({
				...item,
				paying: roundToJiao(item.paying),
				payed: roundToJiao(item.payed),
				purchase: roundToJiao(item.purchase)
			}))
			this.setData({
				list: processedList
			})
		})
	},
	automaticLogon() {
		return new Promise((resolve, reject) => {
			accountLogin({
				username: '18697731337',
				password: '123456'
			}).then(res => {
				const token = res?.data?.token;
				if (!token) {
					toast('登录失败')
					return reject(res)
				}
				wx.setStorageSync('token', token)
				resolve(token)
			}).catch(err => {
				toast('登录失败')
				return reject(err)
			})
		})
	}
})